<?php

/** WebSocket  服务器
 */
namespace app\Console;
use app\common\model\AdminNotify;
use app\common\utils\Redis;
use think\console\Command;

use think\console\Input;
use think\console\Output;

class WebSocket extends  Command
{
    const PORT = WEBSOCKET_PORT;
    const FD_PREFIX="ws_";
    const ADMIN_NOTIFY_CLIENT='ad_notify';
    // Server 实例
    protected $server;

    protected function configure(){
        $this->setName('websocketserver:start')->setDescription('Start WebSocket Server!');


    }
    protected function execute(Input $input, Output $output){

        $this->server =new \swoole_websocket_server('0.0.0.0',self::PORT, SWOOLE_PROCESS, SWOOLE_SOCK_TCP );

        // 设置回调函数
        $this->server->on("open", [$this, 'onOpen']);

        //swoole_client connection listener
        $this->server->on("message",[$this,'onMessage']);

        $this->server->on("request", [$this,'onRequest']);

        $this->server->on("close", [$this, 'onClose']);

        $this->server->start();


    }

    public function onOpen($ws,  $request){

        //保存 连接的客户端
        $client_type =$request->get['client_type'];
        if('admin_notify' == $client_type)
        {
            $redis = Redis::instance();
            $redis->sAdd(self::FD_PREFIX.self::ADMIN_NOTIFY_CLIENT,$request->fd);
        }
        
    }

    public function onMessage($ws,$frame){

        $ws->push($frame->fd,"server:{$frame->data}");
    }
    //Client 关闭触发
    public function onClose($ws, $fd) {
       // echo "clientid:{$fd}\n";
         $redis = Redis::instance();
         $redis->sRem(self::FD_PREFIX.self::ADMIN_NOTIFY_CLIENT,$fd);
    }


    public function onRequest(\swoole_http_request $request,\swoole_http_response $response) {

        if( $request->get['auth'] !='0e541bf02aab56ce6e7e8c3dfae7f77a'){
            return ;
        }
       // dump($request);

        $param =json_decode($request->get['params'],true);
        
        $redis = Redis::instance();
        $fds= $redis->sMembers(self::FD_PREFIX.self::ADMIN_NOTIFY_CLIENT);
        
      //  dump($fds);
       
        
        if($param['op'] == 'add')
        {
            AdminNotify::incrNotifyNum($param['notify_type'],$param['notify_num']);
        }else if($param['op'] == 'sub')
        {
            AdminNotify::descNotifyNum($param['notify_type'],$param['notify_num']);
        }
        
        unset($param['auth']);
        
        foreach ($fds as $fd)
        {
            $this->server->push($fd,$request->get['params']);
        }
//        switch ($request->get['type']){
//
//        }
    }

}